package com.ctvit.sjk.knowledge.dataset.controller;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ctvit.sjk.knowledge.app.service.ITabAppService;
import com.ctvit.sjk.knowledge.core.constant.KnowledgeConstant;
import com.ctvit.sjk.knowledge.core.enums.QueryTypeEnum;
import com.ctvit.sjk.knowledge.core.controller.KnowledgeController;
import com.ctvit.sjk.knowledge.core.page.TableRecordInfo;
import com.ctvit.sjk.knowledge.dataset.pojo.domain.TabDataset;
import com.ctvit.sjk.knowledge.dataset.pojo.dto.DatasetCreateDTO;
import com.ctvit.sjk.knowledge.dataset.pojo.dto.DatasetUpdateDTO;
import com.ctvit.sjk.knowledge.dataset.pojo.vo.DatasetGetVO;
import com.ctvit.sjk.knowledge.dataset.service.ITabDatasetService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 知识库Controller
 *
 * @author heyingcheng
 * @date 2025/3/22
 */
@Slf4j
@RestController
@RequestMapping("knowledge/dataset")
public class TabDatasetController extends KnowledgeController {

    private final ITabDatasetService tabDatasetService;

    private final ITabAppService tabAppService;

    public TabDatasetController(ITabDatasetService tabDatasetService, ITabAppService tabAppService) {
        this.tabDatasetService = tabDatasetService;
        this.tabAppService = tabAppService;
    }

    /**
     * 查询知识库列表
     */
    @GetMapping("{pageNum}/{pageSize}")
    public TableRecordInfo list(@PathVariable int pageNum,
                                @PathVariable int pageSize,
                                @RequestParam(value = "select_user_id", defaultValue = "all") String type,
                                @RequestParam(defaultValue = "") String name) {
        LambdaQueryWrapper<TabDataset> wrapper = new LambdaQueryWrapper<>();
        if (QueryTypeEnum.MY.getCode().equals(type)) {
            wrapper.eq(TabDataset::getCreateId, CREATE_ID);
        }
        wrapper.like(StringUtils.isNotBlank(name), TabDataset::getDatasetName, name);
        wrapper.orderByDesc(TabDataset::getUpdateTime);

        startPage(pageNum, pageSize);
        List<TabDataset> list = tabDatasetService.list(wrapper);
        return getRecordTable(list.stream().map(DatasetGetVO::new).collect(Collectors.toList()), pageNum, pageSize);
    }

    /**
     * 获取知识库详细信息
     */
    @GetMapping
    public AjaxResult list() {
        LambdaQueryWrapper<TabDataset> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(TabDataset::getUpdateTime);

        List<TabDataset> list = tabDatasetService.list(wrapper);
        return success(list.stream().map(DatasetGetVO::new).collect(Collectors.toList()));
    }

    /**
     * 创建知识库
     */
    @Log(title = "知识库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult create(@RequestBody @Validated DatasetCreateDTO dto) {
        TabDataset entity = new TabDataset();
        entity.setDatasetId(IdWorker.getIdStr());
        entity.setDatasetName(dto.getName());
        entity.setDatasetDesc(dto.getDesc());
        entity.setDatasetType(dto.getType());
        entity.setEmbeddingModelId(dto.getEmbeddingModelId());
        entity.setMetadata(KnowledgeConstant.JSON_OBJECT_EMPTY);
        entity.setCreateId(CREATE_ID);
        entity.setCreateTime(LocalDateTime.now());
        entity.setUpdateId(CREATE_ID);
        entity.setUpdateTime(LocalDateTime.now());

        if (tabDatasetService.save(entity)) {
            JSONObject json = new JSONObject();
            json.put("id", entity.getDatasetId());
            return success(json);
        }

        return AjaxResult.error();
    }

    /**
     * 获取知识库详细信息
     */
    @GetMapping("{datasetId}")
    public AjaxResult get(@PathVariable String datasetId) {
        return success(tabDatasetService.get(datasetId));
    }

    /**
     * 删除知识库
     */
    @Log(title = "知识库", businessType = BusinessType.DELETE)
    @PostMapping("remove")
    public AjaxResult batchRemove(@RequestBody List<String> ids) {
        LambdaUpdateWrapper<TabDataset> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TabDataset::getUpdateId, CREATE_ID);
        wrapper.set(TabDataset::getUpdateTime, LocalDateTime.now());
        wrapper.in(TabDataset::getDatasetId, ids);
        return toAjax(tabDatasetService.remove(wrapper));
    }

    /**
     * 删除知识库
     */
    @Log(title = "知识库", businessType = BusinessType.DELETE)
    @DeleteMapping("{datasetId}")
    public AjaxResult remove(@PathVariable String datasetId) {
        LambdaUpdateWrapper<TabDataset> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(TabDataset::getUpdateId, CREATE_ID);
        wrapper.set(TabDataset::getUpdateTime, LocalDateTime.now());
        wrapper.eq(TabDataset::getDatasetId, datasetId);
        return toAjax(tabDatasetService.remove(wrapper));
    }

    /**
     * 获取知识库应用信息
     */
    @GetMapping("{datasetId}/application")
    public AjaxResult getApplication(@PathVariable String datasetId) {
        return success(tabAppService.listByDatasetId(datasetId));
    }

    /**
     * 获取知识库应用信息
     */
    @PutMapping("{datasetId}")
    public AjaxResult update(@PathVariable String datasetId, @RequestBody @Validated DatasetUpdateDTO dto) {
        return success(tabDatasetService.update(datasetId, dto, CREATE_ID));
    }

}
